<template>
  <div class="home">
    <!-- <HotelSelector
      :visible="showHotelDialog"
      @close="showHotelDialog = false"
    ></HotelSelector> -->
    <div>
      <CurrentDate title="Hotel Dashboard"></CurrentDate>
      <CollapsibleSection
        title="1. Platform Overview"
        :tooltip-content="['This section will be updated weekly']"
        @toggle-collapse="handleCollapse"
        :panelIndex="0"
        :isExpanded="panelStates[0]"
      ></CollapsibleSection>

      <ResponseRate v-if="!panelStates[0]"></ResponseRate>

      <!-- 修改后（添加占位元素保持布局） -->
      <div class="pieEcharts" v-if="!panelStates[0]" style="margin-top: 20px">
        <ReviewBySources :class="{ 'full-width': !mediaSwitchState }" />
        <div v-if="!mediaSwitchState" class="chart-placeholder"></div>
        <!-- 新增占位 -->
        <SocialMediaPlatform v-if="mediaSwitchState" />
      </div>

      <!-- 第一组图表折叠组件：保持原有样式，仅添加折叠功能 -->
      <!-- <CollapsibleSection
        style="margin-top: 20px"
        v-if="!panelStates[0]"
        :tooltip-title="'Score Distribution'"
        @toggle-collapse="handleCollapse"
        :panelIndex="2"
        :isExpanded="panelStates[2]"
        :showInfoIcon="false"
        title="  "
      ></CollapsibleSection> -->
      <!-- <div class="pieEcharts" v-if="!panelStates[0] && !panelStates[2]">
        <GlobalScore></GlobalScore>
        <SocialMediaSocore></SocialMediaSocore>
      </div> -->

      <WhereToLook
        v-if="!panelStates[0]"
        :highlight="highlightData"
        :issue="issueData"
        :suggestion="suggestionData"
      ></WhereToLook>
      <CollapsibleSection
        title="2. Performance Analytics"
        :tooltip-content="['  This section will be updated daily']"
        @toggle-collapse="handleCollapse"
        :panelIndex="1"
        :isExpanded="panelStates[1]"
      ></CollapsibleSection>

      <div ref="stickyWrapper" class="sticky-wrapper">
        <div ref="fixedContainer" class="fixed-container">
          <!-- 酒店选择器（放在最左侧，突出重要性） -->

          <PlatformPickerHome v-if="!panelStates[1]"></PlatformPickerHome>
          <DateTimePickerHome
            v-if="!panelStates[1]"
            @date-change="handleDateChange"
          ></DateTimePickerHome>
        </div>
        <div ref="placeholder" class="placeholder"></div>
      </div>

      <CirPie v-if="!panelStates[1]" :categories="categories"></CirPie>
      <!-- <CollapsibleSection
        v-if="!panelStates[1]"
        style="margin-top: 20px"
        title=""
        :tooltip-title="'Performance Trend'"
        @toggle-collapse="handleCollapse"
        :panelIndex="3"
        :isExpanded="panelStates[3]"
        :showInfoIcon="false"
      ></CollapsibleSection> -->
      <!-- <div class="vertical-charts" v-if="!panelStates[1] && !panelStates[3]">
        <CustomerJourneyHome></CustomerJourneyHome>
        <SentimentTre></SentimentTre>
      </div> -->
      <div v-if="!panelStates[1]"><Fact :categories="categories" /></div>
      <div class="progress" v-if="!panelStates[1]">
        <ProgressNeg
          :strengths="strengthsData"
          :is-parent-loading="isLoading"
        ></ProgressNeg>
        <ProgressPos
          :improvements="improvementsData"
          :is-parent-loading="isLoading"
        ></ProgressPos>
      </div>

      <div class="LanAndCountry" v-if="!panelStates[1]">
        <Countries :countries="countries"></Countries>
        <Languages :travelTypes="travelTypes"></Languages>
      </div>
      <!-- 修改后（正确版本） -->
      <!-- <CollapsibleSection
        v-if="!panelStates[1]"
        style="margin-top: 20px"
        title=""
        :tooltip-title="'Platform Distribution'"
        @toggle-collapse="handleCollapse"
        :panelIndex="4"
        :isExpanded="panelStates[4]"
        :showInfoIcon="false"
      ></CollapsibleSection> -->
      <!-- <PlatForm v-if="!panelStates[1] && !panelStates[4]"></PlatForm> -->
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex"; // 关键：导入 mapActions
import CurrentDate from "@components/common/CurrentDate.vue";
import CollapsibleSection from "@components/common/CollapsibleSection.vue";
import ResponseRate from "@views/home/components/ResponseRate.vue";
import ReviewBySources from "@views/home/components/echarts/CirPie/ReviewBySources.vue";
import SocialMediaPlatform from "@views/home/components/echarts/CirPie/SocialMediaPlatform.vue";
import GlobalScore from "@views/home/components/echarts/CirPie/GlobalScore.vue";
import SocialMediaSocore from "@views/home/components/echarts/CirPie/SocialMediaSocore.vue";
import WhereToLook from "@views/home/components/WhereToLook.vue";
import Fact from "@views/home/components/Fact.vue";
import DateTimePickerHome from "@views/home/components/DateTimePickerHome.vue";
import PlatformPickerHome from "@views/home/components/PlatformPickerHome.vue";
import HotelSelector from "@views/home/components/HotelSelector.vue";
import CirPie from "@views/home/components/echarts/CirPie/CirPie.vue";
import CustomerJourneyHome from "@views/home/components/echarts/LinePie/CustomerJourneyHome.vue";
import SentimentTre from "@views/home/components/echarts/LinePie/SentimentTre.vue";
import ProgressNeg from "@views/home/components/echarts/Progress/ProgressNeg.vue";
import ProgressPos from "@views/home/components/echarts/Progress/ProgressPos.vue";
import Languages from "@views/home/components/echarts/BarChart/Languages.vue";
import Countries from "@views/home/components/echarts/BarChart/Countries.vue";
import Sentiments from "@views/home/components/echarts/BarChart/Sentiments.vue";
import Traveller from "@views/home/components/echarts/BarChart/Traveller.vue";
import PlatForm from "@views/home/components/echarts/DoughnutChart/PlatForm.vue";
import { getDashboardDynamic, getDashboardMorning } from "@/api/information.js";
export default {
  name: "HotelDashboard",
  components: {
    CurrentDate,
    CollapsibleSection,
    ResponseRate,
    ReviewBySources,
    SocialMediaPlatform,
    GlobalScore,
    SocialMediaSocore,
    WhereToLook,
    Fact,
    DateTimePickerHome,
    PlatformPickerHome,
    HotelSelector,
    CirPie,
    CustomerJourneyHome,
    SentimentTre,
    ProgressNeg,
    ProgressPos,
    Languages,
    Countries,
    Sentiments,
    Traveller,
    PlatForm,
  },
  data() {
    return {
      // 新增：存储进度条数据

      strengthsData: null, // 用于ProgressNeg的strengths数据
      improvementsData: null, // 用于ProgressPos的improvements数据
      isFirstDateChange: true,
      isLoading: false, // 控制当前组件的加载状态
      //morning
      highlightData: null, // 存储highlight数据
      issueData: null, // 存储issue数据
      suggestionData: null, // 存储suggestion数据
      showHotelDialog: false,
      fixedConfig: {
        triggerOffset: 20, // 触发固定的提前量(px)
        fixedTop: 8, // 固定后的顶部距离(px)
      },
      initialLoad: true,
      panelStates: {
        0: false,
        1: false,
        2: false,
        3: false,
        4: false,
        5: false,
        6: false,
        7: false,
      },
      selectedPlatforms: [],
      dateRange: null,
      frequency: "",
      startDate: "",
      endDate: "",
      categories: {},
      countries: [],
      travelTypes: [],
      isFixed: false,
      scrollHandler: null,
      containerTop: 0,
      containerWidth: 0,
      containerLeft: 0,
      originalStyles: {},
      bodyPaddingLeft: 0,
      resizeObserver: null,
    };
  },
  methods: {
    ...mapActions("hotel", ["fetchHotelList"]), // 引入获取酒店列表的 action
    handleCollapse(panelData) {
      this.panelStates[panelData.panelIndex] = panelData.isExpanded;
    },
    async handleDateChange(params) {
      // 改为async方法
      this.dateRange = params.dateRange;
      this.frequency = params.frequency;
      if (this.dateRange?.length === 2) {
        this.startDate = this.formatDate(this.dateRange[0]);
        this.endDate = this.formatDate(this.dateRange[1]);
      }
      if (this.isFirstDateChange) {
        this.isFirstDateChange = false;
        return;
      }

      this.isLoading = true; // 开始加载，子组件显示"Loading new data..."
      try {
        // 等待两个异步请求都完成
        await Promise.all([
          this.getDashboardDynamicData(),
          this.getDashboardMorningData(),
        ]);
      } catch (error) {
        console.error("数据加载失败:", error);
      } finally {
        // 无论成功失败，都关闭加载状态
        this.isLoading = false;
      }
    },
    formatDate(date) {
      if (!date) return null;
      const d = new Date(date);
      if (isNaN(d.getTime())) return null;
      return [
        d.getFullYear(),
        (d.getMonth() + 1).toString().padStart(2, "0"),
        d.getDate().toString().padStart(2, "0"),
      ].join("-");
    },
    async getDashboardDynamicData() {
      if (!this.currentHotelId) {
        this.$message.warning("Please choose a hotel first");
        router.push("/login");
        return;
      }
      // if (this.initialLoad) {
      //   this.initialLoad = false;
      //   return;
      // }
      try {
        const res = await getDashboardDynamic({
          hotelId: this.currentHotelId,
          startDate: this.startDate,
          endDate: this.endDate,
          frequency: this.frequency,
          sources: this.$store.state.dashBoard.selectedPlatforms.join(","),
        });
        if (res.code === 200) {
          console.log("1111111111饼图返回的数据", res, res.data.categories);
          this.categories = res.data.categories || {};
          this.countries = res.data.countries || [];
          this.travelTypes = res.data.travelTypes || [];
        } else {
          this.categories = {};
          this.isEmptyCategories = true;
          // this.$message.error("Failed to load data. Please try again.");
        }
      } catch (error) {
        this.categories = {};
        this.$message.error("Server error. Please try again later.");
      }
    },
    async getDashboardMorningData() {
      if (!this.currentHotelId) {
        this.$message.warning("Please choose a hotel first");
        router.push("/login");
        return;
      }
      // if (this.initialLoad) {
      //   this.initialLoad = false;
      //   return;
      // }
      try {
        const res = await getDashboardMorning({
          hotelId: this.currentHotelId,
          startDate: this.startDate,
          endDate: this.endDate,
          frequency: this.frequency,
          sources: this.$store.state.dashBoard.selectedPlatforms.join(","),
        });
        if (res.code === 200) {
          this.highlightData = res.data.highlight;
          this.issueData = res.data.issue;
          this.suggestionData = res.data.suggestion;
          this.strengthsData = res.data.strengths; // 传递给ProgressNeg
          this.improvementsData = res.data.improvements; // 传递给ProgressPos

          // 新增：第一次请求成功后存入localStorage
          localStorage.setItem(
            "hotelStrengths",
            JSON.stringify(res.data.strengths)
          );
          localStorage.setItem(
            "hotelImprovements",
            JSON.stringify(res.data.improvements)
          );
          // this.categories = res.data.categories || {};
          // this.countries = res.data.countries || [];
          // this.travelTypes = res.data.travelTypes || [];
        } else {
          // this.categories = {};
          // this.isEmptyCategories = true;
          // // this.$message.error("Failed to load data. Please try again.");
        }
      } catch (error) {
        // this.categories = {};
        this.$message.error("Server error. Please try again later.");
      }
    },
    handleScroll() {
      if (!this.$refs.fixedContainer) return;

      // 直接计算不使用requestAnimationFrame
      const scrollTop =
        window.pageYOffset || document.documentElement.scrollTop;
      const container = this.$refs.fixedContainer;
      const placeholder = this.$refs.placeholder;

      // 精确计算触发点（容器顶部 - 预设偏移量）
      const triggerPoint = this.containerTop - this.fixedConfig.triggerOffset;

      if (scrollTop >= triggerPoint && !this.isFixed) {
        this.fixElement(container, placeholder);
      } else if (scrollTop < triggerPoint && this.isFixed) {
        this.unfixElement(container, placeholder);
      }
    },
    getContainerLeft(element) {
      if (!element) return 0;
      try {
        const rect = element.getBoundingClientRect();
        return rect.left + window.scrollX;
      } catch (e) {
        console.error("计算容器位置出错:", e);
        return 0;
      }
    },
    fixElement(container, placeholder) {
      if (!container || !placeholder) return;

      // 保存原始样式
      this.originalStyles = {
        position: container.style.position,
        top: container.style.top,
        left: container.style.left,
        width: container.style.width,
        zIndex: container.style.zIndex,
        paddingLeft: container.style.paddingLeft,
      };

      // 获取容器位置和尺寸
      const rect = container.getBoundingClientRect();
      this.containerWidth = rect.width;
      this.containerLeft = rect.left + window.scrollX;

      // 设置占位元素
      placeholder.style.height = `${rect.height}px`;
      placeholder.style.width = `${rect.width}px`;

      const topOffset = 8; // ← 这里调整固定后的顶部距离
      // 精确计算左侧位置（解决可能存在的布局偏移）
      this.containerLeft = Math.max(0, this.getContainerLeft(container));

      // 应用固定定位样式
      container.style.position = "fixed";
      container.style.top = `${topOffset}px`;
      container.style.left = `${this.containerLeft}px`;
      container.style.width = `${this.containerWidth}px`;
      container.style.zIndex = "1000";
      container.style.transition = "none"; // 禁用过渡效果

      this.isFixed = true;

      // 强制重绘
      container.getBoundingClientRect();
    },
    unfixElement(container, placeholder) {
      if (!container || !placeholder) return;

      // 恢复原始样式
      container.style.position = this.originalStyles.position || "";
      container.style.top = this.originalStyles.top || "";
      container.style.left = this.originalStyles.left || "";
      container.style.width = this.originalStyles.width || "";
      container.style.zIndex = this.originalStyles.zIndex || "";
      container.style.transition = "";

      // 重置占位元素
      placeholder.style.height = "0";
      placeholder.style.width = "0";

      this.isFixed = false;
    },
    initScrollListener() {
      this.$nextTick(() => {
        if (!this.$refs.stickyWrapper) return;

        // 立即计算初始位置
        this.calculateContainerPosition();

        // 简化滚动监听
        this.scrollHandler = this.handleScroll;
        window.addEventListener("scroll", this.scrollHandler, {
          passive: true,
        });

        // 使用防抖的resize监听
        this.resizeObserver = new ResizeObserver(
          this.debounce(() => {
            this.calculateContainerPosition();
            if (this.isFixed) {
              this.updateFixedPosition();
            }
          }, 100)
        );

        this.resizeObserver.observe(this.$refs.stickyWrapper);
      });
    },
    calculateContainerPosition() {
      const rect = this.$refs.stickyWrapper.getBoundingClientRect();
      this.containerTop = rect.top + window.scrollY;
    },

    updateFixedPosition() {
      const container = this.$refs.fixedContainer;
      const rect = container.getBoundingClientRect();
      container.style.left = `${rect.left + window.scrollX}px`;
      container.style.width = `${rect.width}px`;
    },

    debounce(fn, delay) {
      let timer;
      return () => {
        clearTimeout(timer);
        timer = setTimeout(fn, delay);
      };
    },
  },
  computed: {
    mediaSwitchState() {
      return this.$store.state.dashBoard?.mediaSwitch ?? true;
    },
    hotelList() {
      // 直接访问，跳过 mapState
      return this.$store.state.hotel?.hotelList || [];
    },
    currentHotelId() {
      return this.$store.state.hotel.currentHotelId;
    },
  },
  mounted() {
    this.frequency = "WEEK";
    this.$nextTick(() => {
      // 新增：读取本地存储
      const storedStrengths = localStorage.getItem("hotelStrengths");
      const storedImprovements = localStorage.getItem("hotelImprovements");
      this.getDashboardDynamicData();
      // 有本地存储则直接赋值（第二次进入）
      if (storedStrengths && storedImprovements) {
        this.strengthsData = JSON.parse(storedStrengths);
        this.improvementsData = JSON.parse(storedImprovements);
      } else {
        // 无存储则请求接口（第一次进入）

        this.getDashboardMorningData();
      }

      // 原有滚动监听逻辑不变
      setTimeout(() => {
        this.initScrollListener();
      }, 100);
    });
  },
  beforeDestroy() {
    if (this.scrollHandler) {
      window.removeEventListener("scroll", this.scrollHandler);
    }
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
    }
  },
};
</script>

<style lang="scss" scoped>
.home {
  flex: 1;
  position: relative;
  .pieEcharts {
    display: flex;
    width: 100%;
    box-sizing: border-box;
    margin-top: 20px;
    gap: 12px;
    > div,
    .chart-placeholder {
      box-sizing: border-box;
      flex: 1;
      min-width: 0;
      max-width: calc(50% - 6px);
      overflow: hidden;
    }
    &:has(> *:only-child) {
      > div {
        max-width: 100%;
      }
    }
    > div {
      margin-right: 0 !important;
    }
  }
  .progress {
    margin-top: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    > * {
      flex: 1;
      & + * {
        margin-left: 12px;
      }
    }
  }
  .pieEcharts,
  .LanAndCountry {
    display: flex;
    width: 100%;
    box-sizing: border-box;
    margin-top: 20px;
    gap: 12px;
    > * {
      box-sizing: border-box;
      flex: 1;
      min-width: 0;
      overflow: hidden;
    }
    .chart-placeholder {
      min-height: 1px;
    }
    &:has(> *:only-child) {
      gap: 0;
      > * {
        width: 100%;
      }
    }
  }

  .sticky-wrapper {
    position: relative;
    width: 100%;
  }
  .vertical-charts {
    display: flex;
    flex-direction: column;
    width: 100%;
    box-sizing: border-box;
    gap: 12px;
    > div {
      width: 100%;
      box-sizing: border-box;
      min-height: 300px;
    }
  }
  .fixed-container {
    width: 100%;
    box-sizing: border-box;
    background-color: #fff; /* 提前设置背景色避免闪烁 */
    padding: 16px;
    border-radius: 8px;
    border: 1px solid #cdcccc;
  }
  .placeholder {
    height: 0;
    width: 0;
    transition: none;
    pointer-events: none;
  }
  .fixed-container.fixed {
    position: fixed;
    top: 8px;
    left: 0;
    width: 100%;
    z-index: 1000;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    will-change: transform; /* 提示浏览器优化 */
    backface-visibility: hidden; /* 防止闪烁 */
    transform: translateZ(0); /* 启用硬件加速 */
  }
}
/* 1. 中屏适配（768px - 1199px）：缩小间距，保持一行两列 */
@media (max-width: 1199px) and (min-width: 1000px) {
  .home .LanAndCountry {
    gap: 12px; /* 缩小间距，适配中屏 */
  }
  .home .LanAndCountry > * {
    // min-height: 250px; /* 适当降低最小高度 */
  }
}

/* 2. 小屏适配（≤767px）：改为一行一列 */
@media (max-width: 1000px) {
  .home .LanAndCountry {
    flex-direction: column; /* 垂直排列 */
    gap: 16px; /* 垂直方向间距 */
  }
  .home .LanAndCountry > * {
    width: 100% !important; /* 强制占满宽度 */
    // min-height: 220px; /* 进一步降低高度，适配手机 */
  }
  .home .progress {
    flex-direction: column; /* 垂直排列 */
    gap: 16px; /* 垂直方向间距 */
  }
  .home .progress > * {
    width: 100% !important; /* 强制占满宽度 */
    // min-height: 220px; /* 进一步降低高度，适配手机 */
  }
}
</style>
